package com.u3k.sdk;

import android.content.Context;
import com.u3k.app.SdkMain;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class MiddleMainManager
{
  private static MiddleMainManager _instance;
  //Key 是hexStr，Object就是MiddleMainClass，动态加载出来的
  Map<String, Object> middleMainMap = new HashMap();

  public static synchronized MiddleMainManager getInstance(Context paramContext)
  {
    if (_instance == null) {
      _instance = new MiddleMainManager();
    }
    return _instance;
  }

  /**
   *
   * @param paramContext
   * @param hexStr  appKey + channel，版本的Hex形式字符串，可以认为是一个唯一标记
   * @return
   */
  public static String getMidexFolder(Context paramContext, String hexStr)
  {
    String str = getBaseLibFolder(paramContext, hexStr);
    return str + FileNameConst.getMidDex();
  }

  /**
   *
   * @param paramContext
   * @param hexStr  appKey + channel，版本的Hex形式字符串，可以认为是一个唯一标记
   * @return
   */
  public static String getBaseLibFolder(Context paramContext, String hexStr)
  {
    String str1 = paramContext.getFilesDir() + File.separator + hexStr + File.separator + FileNameConst.getBaseLibFolder() + File.separator;//base lib
    String str2 = (String)SharePrefrenceUtil.getObject(paramContext, "middle_version", null);//此处有问题，应该崩溃才对
    if (str2 != null) {
      str1 = str1 + str2 + File.separator;
    }
    File localFile = new File(str1);
    if (!localFile.exists()) {
      localFile.mkdirs();
    }
    return str1;
  }

  public String createMiddleMainObject(Context paramContext, String appKey, String channel)
  {
    g.a("MiddleHelper", "init appId=" + appKey + ", channelId=" + channel);
    String hexStr = createHex(appKey, channel);
    if (hexStr == null) {
      return null;
    }
    if (this.middleMainMap.get(hexStr) != null) {
      return hexStr;
    }
    try
    {
      String strMidexPath = getMidexFolder(paramContext, hexStr);
      g.a("MiddleHelper", "init dexPath=" + strMidexPath);
      File midexFile = new File(strMidexPath);
      if (midexFile.exists())
      {
        g.a("MiddleHelper", "init midDex exists");
        if (putMiddleMainMap(paramContext, appKey, channel, hexStr)) {
          return hexStr;
        }
        midexFile.delete();
      }
      c.writeStringToFile(j.midexFileData, strMidexPath);
      if (!putMiddleMainMap(paramContext, appKey, channel, hexStr)) {
        return null;
      }
    }
    catch (Exception localException)
    {
      g.a("MiddleHelper", "init Exception=" + localException);
      return null;
    }
    return hexStr;
  }

  /**
   * 生成middleMain类对象，放在map当中
   * @param paramContext
   * @param appKey
   * @param channel
   * @param hexStr 唯一标识符，由appk + Md5(channel + version)组成
   * @return
   */
  private boolean putMiddleMainMap(Context paramContext, String appKey, String channel, String hexStr)
  {
    g.a("MiddleHelper", "callMiddleInit");
    boolean ret = false;
    String strMidexFolder = getMidexFolder(paramContext, hexStr);
    String strBaseLibFolder = getBaseLibFolder(paramContext, hexStr) + FileNameConst.getOptFolder();
    File baseLibFile = new File(strBaseLibFolder);
    if (!baseLibFile.exists()) {
      baseLibFile.mkdirs();
    }
    h localh = new h(strMidexFolder, strBaseLibFolder, null, SdkMain.class.getClassLoader());
    String[][] arrayOfString = { j.a, j.b, j.d, j.e, j.f, j.g, j.h, j.i, j.j, j.k };
    try
    {
      Class middleMainClass = localh.loadClass(FileNameConst.getMiddleMain());//MiddleMain 加载起来
      Method middleMainInstanceMethod = middleMainClass.getDeclaredMethod("getInstance", null);
      middleMainInstanceMethod.setAccessible(true);
      Object MiddleMainObject = middleMainInstanceMethod.invoke(null, null);
      Method[] arrayOfMethod1 = middleMainClass.getMethods();
      Object[] arrayOfObject = { paramContext, appKey, channel, hexStr, "she1.1.0", "U3kSDK_she1.1.0_1", arrayOfString };
      //执行MiddleMain.init函数
      for (Method localMethod2 : arrayOfMethod1) {
        if (localMethod2.getName().equals("init"))
        {
          localMethod2.invoke(MiddleMainObject, new Object[] { arrayOfObject });
          g.a("MiddleHelper", "callMiddleInit  finish init");
          break;
        }
      }
      this.middleMainMap.put(hexStr, MiddleMainObject);
      ret = true;
    }
    catch (Exception localException)
    {
      g.a("MiddleHelper", "callMiddleInit  Exception=" + localException.getMessage());
      localException.printStackTrace();
    }
    return ret;
  }

  public Object a(String paramString1, Context paramContext, String paramString2, Object... paramVarArgs)
  {
    g.a("MiddleHelper", "invokeModuleMethod  pulicName=" + paramString2);
    ClassLoader localClassLoader = getInstance(paramContext).a(paramString1);
    if (localClassLoader == null)
    {
      g.a("MiddleHelper", "invokeModuleMethod loader null");
      return "error";
    }
    try
    {
      g.a("MiddleHelper", "invokeModuleMethod loader.loadClass");
      Class localClass = localClassLoader.loadClass("com.u3k.app.mid.core.ModuleApiManager");
      Method localMethod1 = localClass.getMethod("getInstance", new Class[] { Context.class });
      localMethod1.setAccessible(true);
      Object localObject1 = localMethod1.invoke(null, new Object[] { paramContext });
      Method[] arrayOfMethod1 = localClass.getMethods();
      Object localObject2 = null;
      for (Method localMethod2 : arrayOfMethod1) {
        if (localMethod2.getName().equals("invokeModuleApiMethod"))
        {
          localObject2 = localMethod2;
          break;
        }
      }
      g.a("MiddleHelper", "invokeModuleMethod invokeModuleApiMethod=" + localObject2);
      ((Method)localObject2).setAccessible(true);
      return ((Method)localObject2).invoke(localObject1, new Object[] { paramString2, paramVarArgs });
    }
    catch (Exception localException)
    {
      if (localException != null) {
        g.a("MiddleHelper", "invokeModuleApiMethod Exception=", localException);
      }
    }
    return "error";
  }

  private ClassLoader a(String paramString)
  {
    Object localObject = this.middleMainMap.get(paramString);
    if (localObject != null) {
      return localObject.getClass().getClassLoader();
    }
    return null;
  }

  /*
 生成appkey + md5散列信息
   */
  private String createHex(String appKey, String channel)
  {
    if (appKey == null) {
      return null;
    }
    if (channel != null) {
      return appKey + createMd5String(new StringBuilder().append(channel).append("U3kSDK_she1.1.0_1").toString());
    }
    return appKey;
  }

  /**
   * 生成一个字符串的md5，并且用十六进制字符串形式表示出来
   * @param string
   * @return
   */
  private String createMd5String(String string)
  {
    byte[] md5;
    try
    {
      md5= MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
    }
    catch (NoSuchAlgorithmException localNoSuchAlgorithmException)
    {
      localNoSuchAlgorithmException.printStackTrace();
      return null;
    }
    catch (UnsupportedEncodingException localUnsupportedEncodingException)
    {
      localUnsupportedEncodingException.printStackTrace();
      return null;
    }
    StringBuilder Md5HexBuilder = new StringBuilder(md5.length * 2);
    for (int k : md5)
    {
      if ((k & 0xFF) < 16) {
        Md5HexBuilder.append("0");
      }
      Md5HexBuilder.append(Integer.toHexString(k & 0xFF));
    }
    return Md5HexBuilder.toString();
  }
}


